<template>
  <div class="route-plan">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="配送日期">
          <el-date-picker
            v-model="searchForm.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="配送司机">
          <el-select v-model="searchForm.driverId" placeholder="请选择司机" clearable>
            <el-option
              v-for="item in driverOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配送区域">
          <el-cascader
            v-model="searchForm.area"
            :options="areaOptions"
            placeholder="请选择区域"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 路线规划区域 -->
    <el-row :gutter="20" class="route-container">
      <!-- 左侧订单列表 -->
      <el-col :span="8">
        <el-card class="order-card">
          <template #header>
            <div class="card-header">
              <span>待配送订单</span>
              <el-button type="primary" @click="handleAutoRoute">
                <el-icon><SetUp /></el-icon>智能规划
              </el-button>
            </div>
          </template>
          
          <el-scrollbar height="calc(100vh - 300px)">
            <div 
              v-for="order in unassignedOrders" 
              :key="order.id"
              class="order-item"
              draggable
              @dragstart="handleDragStart(order)"
              @dragend="handleDragEnd"
            >
              <div class="order-info">
                <div class="order-no">{{ order.orderNo }}</div>
                <div class="order-address">{{ order.address }}</div>
                <div class="order-detail">
                  <span>{{ order.customerName }}</span>
                  <span>{{ order.phone }}</span>
                </div>
              </div>
              <el-tag size="small" :type="getOrderTypeTag(order)">
                {{ getOrderTypeText(order) }}
              </el-tag>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>

      <!-- 右侧路线规划 -->
      <el-col :span="16">
        <el-card class="route-card">
          <template #header>
            <div class="card-header">
              <span>配送路线</span>
              <div class="header-actions">
                <el-button type="success" @click="handleSaveRoute" :disabled="!hasRouteChanged">
                  保存路线
                </el-button>
                <el-button @click="handleExportRoute">
                  <el-icon><Download /></el-icon>导出路线
                </el-button>
              </div>
            </div>
          </template>

          <div class="route-list">
            <div 
              v-for="(driver, index) in routePlan" 
              :key="driver.id"
              class="route-item"
              @dragover.prevent
              @drop="handleDrop(driver)"
            >
              <div class="driver-info">
                <el-avatar :size="40" :src="driver.avatar" />
                <div class="driver-detail">
                  <div class="driver-name">{{ driver.name }}</div>
                  <div class="driver-stats">
                    <el-tag size="small">{{ driver.orders.length }}单</el-tag>
                    <el-tag size="small" type="success">预计{{ driver.estimatedTime }}分钟</el-tag>
                  </div>
                </div>
                <el-button 
                  type="primary" 
                  link
                  @click="handlePreviewRoute(driver)"
                >
                  预览路线
                </el-button>
              </div>

              <el-divider>配送路线</el-divider>

              <div class="order-list">
                <el-empty v-if="!driver.orders.length" description="暂无配送订单" />
                <template v-else>
                  <div 
                    v-for="(order, orderIndex) in driver.orders" 
                    :key="order.id"
                    class="route-order-item"
                    :class="{ 'is-dragging': isDragging && currentDragOrder?.id === order.id }"
                    draggable
                    @dragstart="handleDragStart(order)"
                    @dragend="handleDragEnd"
                    @dragover.prevent
                    @drop="handleReorder(driver, orderIndex)"
                  >
                    <div class="order-sequence">{{ orderIndex + 1 }}</div>
                    <div class="order-info">
                      <div class="order-no">{{ order.orderNo }}</div>
                      <div class="order-address">{{ order.address }}</div>
                      <div class="order-detail">
                        <span>{{ order.customerName }}</span>
                        <span>{{ order.phone }}</span>
                      </div>
                    </div>
                    <div class="order-actions">
                      <el-button 
                        type="danger" 
                        link
                        @click="handleRemoveOrder(driver, order)"
                      >
                        移除
                      </el-button>
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 路线预览弹窗 -->
    <el-dialog
      title="路线预览"
      v-model="previewVisible"
      width="80%"
      destroy-on-close
    >
      <div class="route-preview">
        <div class="preview-map">
          <!-- 这里集成地图组件 -->
          <div class="map-placeholder">地图区域</div>
        </div>
        <div class="preview-info">
          <div class="info-header">
            <div class="driver-info">
              <el-avatar :size="50" :src="currentPreview?.avatar" />
              <div class="driver-detail">
                <div class="driver-name">{{ currentPreview?.name }}</div>
                <div class="driver-contact">{{ currentPreview?.phone }}</div>
              </div>
            </div>
            <div class="route-stats">
              <div class="stat-item">
                <div class="label">配送订单</div>
                <div class="value">{{ currentPreview?.orders.length }}单</div>
              </div>
              <div class="stat-item">
                <div class="label">预计里程</div>
                <div class="value">{{ currentPreview?.estimatedDistance }}km</div>
              </div>
              <div class="stat-item">
                <div class="label">预计时间</div>
                <div class="value">{{ currentPreview?.estimatedTime }}分钟</div>
              </div>
            </div>
          </div>
          
          <el-divider>配送路线</el-divider>
          
          <el-steps direction="vertical" :active="1">
            <el-step 
              v-for="(order, index) in currentPreview?.orders"
              :key="order.id"
              :title="order.address"
              :description="order.orderNo"
            >
              <template #icon>
                <div class="step-number">{{ index + 1 }}</div>
              </template>
            </el-step>
          </el-steps>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, Refresh, SetUp, Download,
  Location, Van
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  date: '',
  driverId: '',
  area: []
})

// 拖拽相关
const isDragging = ref(false)
const currentDragOrder = ref<any>(null)

// 预览相关
const previewVisible = ref(false)
const currentPreview = ref<any>(null)

// 模拟数据
const driverOptions = [
  { value: '1', label: '张三' },
  { value: '2', label: '李四' },
  { value: '3', label: '王五' }
]

const areaOptions = [
  {
    value: 'beijing',
    label: '北京市',
    children: [
      {
        value: 'chaoyang',
        label: '朝阳区',
        children: [
          { value: 'area1', label: 'xx街道' }
        ]
      }
    ]
  }
]

const unassignedOrders = ref([
  {
    id: '1',
    orderNo: 'DD20231128001',
    customerName: '张三',
    phone: '13800138000',
    address: '北京市朝阳区xxx街道',
    type: 'normal'
  }
])

const routePlan = ref([
  {
    id: '1',
    name: '张三',
    phone: '13800138000',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    orders: [],
    estimatedTime: 0,
    estimatedDistance: 0
  }
])

// 计算属性
const hasRouteChanged = computed(() => {
  return routePlan.value.some(driver => driver.orders.length > 0)
})

// 方法
const getOrderTypeTag = (order: any) => {
  const map: Record<string, string> = {
    normal: '',
    urgent: 'danger',
    vip: 'warning'
  }
  return map[order.type] || ''
}

const getOrderTypeText = (order: any) => {
  const map: Record<string, string> = {
    normal: '普通订单',
    urgent: '加急订单',
    vip: 'VIP订单'
  }
  return map[order.type] || '普通订单'
}

const handleSearch = () => {
  // 实现搜索逻辑
}

const resetSearch = () => {
  searchForm.value = {
    date: '',
    driverId: '',
    area: []
  }
}

const handleDragStart = (order: any) => {
  isDragging.value = true
  currentDragOrder.value = order
}

const handleDragEnd = () => {
  isDragging.value = false
  currentDragOrder.value = null
}

const handleDrop = (driver: any) => {
  if (!currentDragOrder.value) return
  
  // 如果是从未分配列表拖动
  const orderIndex = unassignedOrders.value.findIndex(o => o.id === currentDragOrder.value.id)
  if (orderIndex > -1) {
    unassignedOrders.value.splice(orderIndex, 1)
    driver.orders.push(currentDragOrder.value)
  } else {
    // 如果是从其他司机的订单列表拖动
    routePlan.value.forEach(d => {
      const index = d.orders.findIndex(o => o.id === currentDragOrder.value.id)
      if (index > -1) {
        d.orders.splice(index, 1)
        driver.orders.push(currentDragOrder.value)
      }
    })
  }
  
  // 更新预计时间
  updateEstimatedTime(driver)
}

const handleReorder = (driver: any, targetIndex: number) => {
  if (!currentDragOrder.value) return
  
  const sourceIndex = driver.orders.findIndex(o => o.id === currentDragOrder.value.id)
  if (sourceIndex > -1) {
    const [order] = driver.orders.splice(sourceIndex, 1)
    driver.orders.splice(targetIndex, 0, order)
    updateEstimatedTime(driver)
  }
}

const handleRemoveOrder = (driver: any, order: any) => {
  const index = driver.orders.findIndex(o => o.id === order.id)
  if (index > -1) {
    driver.orders.splice(index, 1)
    unassignedOrders.value.push(order)
    updateEstimatedTime(driver)
  }
}

const updateEstimatedTime = (driver: any) => {
  // 这里应该根据实际距离计算时间
  driver.estimatedTime = driver.orders.length * 30
  driver.estimatedDistance = driver.orders.length * 5
}

const handleAutoRoute = () => {
  // 实现智能规划逻辑
  ElMessage.success('路线规划完成')
}

const handleSaveRoute = () => {
  // 实现保存路线逻辑
  ElMessage.success('路线保存成功')
}

const handleExportRoute = () => {
  // 实现导出路线逻辑
  ElMessage.success('路线导出成功')
}

const handlePreviewRoute = (driver: any) => {
  currentPreview.value = driver
  previewVisible.value = true
}
</script>

<style scoped lang="scss">
.route-plan {
  .route-container {
    margin-top: 20px;
  }
  
  .order-card {
    height: calc(100vh - 180px);
    
    .order-item {
      padding: 12px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      margin-bottom: 10px;
      cursor: move;
      transition: all 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      .order-info {
        margin-bottom: 8px;
        
        .order-no {
          font-weight: bold;
          margin-bottom: 4px;
        }
        
        .order-address {
          color: #606266;
          margin-bottom: 4px;
        }
        
        .order-detail {
          font-size: 12px;
          color: #909399;
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
  
  .route-card {
    height: calc(100vh - 180px);
    
    .route-list {
      .route-item {
        margin-bottom: 20px;
        padding: 16px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        
        .driver-info {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .driver-detail {
            flex: 1;
            
            .driver-name {
              font-weight: bold;
              margin-bottom: 4px;
            }
            
            .driver-stats {
              display: flex;
              gap: 8px;
            }
          }
        }
        
        .order-list {
          min-height: 100px;
          
          .route-order-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            margin-bottom: 10px;
            cursor: move;
            transition: all 0.3s;
            
            &:hover {
              background-color: #f5f7fa;
            }
            
            &.is-dragging {
              opacity: 0.5;
            }
            
            .order-sequence {
              width: 24px;
              height: 24px;
              border-radius: 50%;
              background-color: #409eff;
              color: #fff;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 12px;
            }
            
            .order-info {
              flex: 1;
              
              .order-no {
                font-weight: bold;
                margin-bottom: 4px;
              }
              
              .order-address {
                color: #606266;
                margin-bottom: 4px;
              }
              
              .order-detail {
                font-size: 12px;
                color: #909399;
                display: flex;
                justify-content: space-between;
              }
            }
          }
        }
      }
    }
  }
  
  .route-preview {
    display: flex;
    gap: 20px;
    height: 600px;
    
    .preview-map {
      flex: 2;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      
      .map-placeholder {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #909399;
        background-color: #f5f7fa;
      }
    }
    
    .preview-info {
      flex: 1;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 20px;
      
      .info-header {
        .driver-info {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 20px;
          
          .driver-detail {
            .driver-name {
              font-weight: bold;
              margin-bottom: 4px;
            }
            
            .driver-contact {
              color: #909399;
            }
          }
        }
        
        .route-stats {
          display: flex;
          justify-content: space-between;
          
          .stat-item {
            text-align: center;
            
            .label {
              color: #909399;
              margin-bottom: 4px;
            }
            
            .value {
              font-size: 20px;
              font-weight: bold;
              color: #409eff;
            }
          }
        }
      }
      
      .step-number {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background-color: #409eff;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style> 